package com.yzkj.cpjxc.business.controller;

import com.yzkj.cpjxc.business.domain.Dickm;
import com.yzkj.cpjxc.business.domain.DickmQueryVo;
import com.yzkj.cpjxc.business.domain.DickmShowVo;
import com.yzkj.cpjxc.business.service.DickmService;
import com.yzkj.cpjxc.business.framework.common.Constants;
import com.yzkj.cpjxc.business.framework.common.Pager;
import com.yzkj.cpjxc.business.framework.utils.DateTimeUtils;
import com.yzkj.cpjxc.business.domain.ZTreeComm;
import com.yzkj.cpjxc.business.system.interceptor.DoLog;
import com.yzkj.cpjxc.business.system.interceptor.Permission;
import com.yzkj.cpjxc.business.domain.JieZhang;
import com.yzkj.cpjxc.business.domain.KmYuEBiao;
import com.yzkj.cpjxc.business.service.KmYuEBiaoService;
import com.yzkj.cpjxc.business.domain.PingZhengQueryVo;
import com.yzkj.cpjxc.business.domain.PingZhengShowVo;
import com.yzkj.cpjxc.business.service.PingZhengService;
import com.yzkj.cpjxc.business.domain.ZhangTao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 科目余额表控制器
 */
@Controller
@RequestMapping("/kmYuEBiao")
public class KmYuEBiaoController extends BaseController {

	@Autowired
	private KmYuEBiaoService kmYuEBiaoService;
	
	@Autowired
	private DickmService dickmService;
	
	@Autowired
	private PingZhengService pingZhengService;

	@RequestMapping("/list")
	@DoLog(cnContent = "查看科目余额列表信息")
	@Permission(name="kmYuEBiao.view")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response, KmYuEBiao qvo) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		//当前账期
		JieZhang jz = (JieZhang) request.getSession().getAttribute(Constants.CURRENT_JIE_ZHANG);
		ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
		
		modelMap.put("minDate", zt.getQyYear() + "-" + StringUtils.leftPad(zt.getQyMonth() + "", 2, "0"));
		modelMap.put("maxDate", jz.getJzYear() + "-" + StringUtils.leftPad(jz.getJzMonth() + "", 2, "0"));

		int jz_year = jz.getJzYear();
		int jz_month = jz.getJzMonth();

		String startTimeStr = jz_year + "-" + StringUtils.leftPad(jz_month + "", 2, "0");
		modelMap.put("startTimeStr", startTimeStr);
		modelMap.put("endTimeStr", startTimeStr);

		return new ModelAndView("kmYuEBiao/list").addAllObjects(modelMap);
	}
	
	@RequestMapping("/ajaxList")
	@DoLog(cnContent = "科目余额列表ajax")
	@Permission(name="kmYuEBiao.view")
	public String ajaxList(HttpServletRequest request, HttpServletResponse response, KmYuEBiao qvo) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		try {
			
			ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
			String startTimeStr = request.getParameter("startTimeStr");
			String endTimeStr = request.getParameter("endTimeStr");
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM");
			Map<String, Date> datemap = null;
			Date startTime = null;
			Date endTime = null;
			String tempDateStr;
			//如果开始时间和结束时间不为空
			if (StringUtils.isNotBlank(startTimeStr) && StringUtils.isNotBlank(endTimeStr)) {
				
				modelMap.put("startTimeStr", startTimeStr);
				modelMap.put("endTimeStr", endTimeStr);
				
				startTimeStr = startTimeStr + "-01";
				endTimeStr = endTimeStr + "-01";
				datemap = DateTimeUtils.getMonthEndDateForStartDate(sdf.parse(endTimeStr));
				startTime = sdf.parse(startTimeStr);
				endTime = datemap.get(Constants.END_TIME);
			}else{
				if (StringUtils.isNotBlank(startTimeStr)) {
					tempDateStr = startTimeStr + "-01";
				}else if (StringUtils.isNotBlank(endTimeStr)){
					tempDateStr = endTimeStr + "-01";
				}else{
					//当前账期
					JieZhang jz = (JieZhang) request.getSession().getAttribute(Constants.CURRENT_JIE_ZHANG);
					int jz_year = jz.getJzYear();
					int jz_month = jz.getJzMonth();
					tempDateStr = jz_year + "-" + StringUtils.leftPad(jz_month + "", 2, "0") + "-01";
				}
				
				datemap = DateTimeUtils.getMonthEndDateForStartDate(sdf.parse(tempDateStr));
				startTime = datemap.get(Constants.START_TIME);
				endTime = datemap.get(Constants.END_TIME);
				
				modelMap.put("startTimeStr", sdf2.format(startTime));
				modelMap.put("endTimeStr", sdf2.format(startTime));
			}
			
			if(startTime.getTime()>=endTime.getTime()){
				modelMap.put("msg", "会计期间：开始期间不能大于结束期间!");
				return this.ajax(response,modelMap);
			}
			
			qvo.setStartTime(startTime);
			qvo.setEndTime(endTime);
			qvo.setZhangTaoId(zt.getUuid());
			
			//通过开始时间获取本年年初时间 一般是  开始时间年的1月1号
			int year = DateTimeUtils.getYear(qvo.getStartTime());
			qvo.setYearStartTime(sdf.parse(year+"-01"+"-01"));

			List<KmYuEBiao> dataList = kmYuEBiaoService.searchList(qvo);
			
			Double qiChuValueJie=0.0;
			Double qiChuValueDai=0.0;
			Double bqfsValueJie=0.0;
			Double bqfsValueDai=0.0;
			Double bnljValueJie=0.0;
			Double bnljValueDai=0.0;
			Double qiMoValueJie=0.0;
			Double qiMoValueDai=0.0;
			
			Iterator<KmYuEBiao> iterator = dataList.iterator();
			KmYuEBiao obj = null;
			
			BigDecimal b1 = null;
			BigDecimal b2 = null;
			
			while(iterator.hasNext()){
				obj = iterator.next();
				if(obj.getQiChuValueJie()==0 &&
						obj.getQiChuValueDai()==0 &&
						obj.getBqfsValueJie()==0 &&
						obj.getBqfsValueDai()==0 &&
						obj.getBnljValueJie()==0 &&
						obj.getBnljValueDai()==0 &&
						obj.getQiMoValueJie()==0 &&
						obj.getQiMoValueDai()==0 &&
						!"6301".equals(obj.getDicCode())//添加---营业外收入展示
					){
					iterator.remove();
					continue;
				}
				
				if(obj.getQiChuValueJie()==0){
					obj.setQiChuValueJie(null);
				}else{
					if("1".equals(obj.getLevelNum())) {
						qiChuValueJie+=obj.getQiChuValueJie();
					}
					
					b1 = new BigDecimal(obj.getQiChuValueJie().toString());
					b2 = new BigDecimal("100");
					obj.setQiChuValueJie(b1.divide(b2).doubleValue());
				}
				
				if(obj.getQiChuValueDai()==0){
					obj.setQiChuValueDai(null);
				}else{
					if("1".equals(obj.getLevelNum())) {
						qiChuValueDai+=obj.getQiChuValueDai();
					}
					
					b1 = new BigDecimal(obj.getQiChuValueDai().toString());
					b2 = new BigDecimal("100");
					obj.setQiChuValueDai(b1.divide(b2).doubleValue());
				}
				
				if(obj.getBqfsValueJie()==0){
					obj.setBqfsValueJie(null);
				}else{
					if("1".equals(obj.getLevelNum())) {
						bqfsValueJie+=obj.getBqfsValueJie();
					}
					
					b1 = new BigDecimal(obj.getBqfsValueJie().toString());
					b2 = new BigDecimal("100");
					obj.setBqfsValueJie(b1.divide(b2).doubleValue());
				}
				
				if(obj.getBqfsValueDai()==0){
					obj.setBqfsValueDai(null);
				}else{
					if("1".equals(obj.getLevelNum())) {
						bqfsValueDai+=obj.getBqfsValueDai();
					}
					
					b1 = new BigDecimal(obj.getBqfsValueDai().toString());
					b2 = new BigDecimal("100");
					obj.setBqfsValueDai(b1.divide(b2).doubleValue());
				}
				
				if(obj.getBnljValueJie()==0){
					obj.setBnljValueJie(null);
				}else{
					if("1".equals(obj.getLevelNum())) {
						bnljValueJie+=obj.getBnljValueJie();
					}
					
					b1 = new BigDecimal(obj.getBnljValueJie().toString());
					b2 = new BigDecimal("100");
					obj.setBnljValueJie(b1.divide(b2).doubleValue());
				}
				
				if(obj.getBnljValueDai()==0){
					obj.setBnljValueDai(null);
				}else{
					if("1".equals(obj.getLevelNum())) {
						bnljValueDai+=obj.getBnljValueDai();
					}
					
					b1 = new BigDecimal(obj.getBnljValueDai().toString());
					b2 = new BigDecimal("100");
					obj.setBnljValueDai(b1.divide(b2).doubleValue());
				}
				
				if(obj.getQiMoValueJie()==0){
					obj.setQiMoValueJie(null);
				}else{
					if("1".equals(obj.getLevelNum())) {
						qiMoValueJie+=obj.getQiMoValueJie();
					}
					
					b1 = new BigDecimal(obj.getQiMoValueJie().toString());
					b2 = new BigDecimal("100");
					obj.setQiMoValueJie(b1.divide(b2).doubleValue());
				}
				
				if(obj.getQiMoValueDai()==0){
					obj.setQiMoValueDai(null);
				}else{
					if("1".equals(obj.getLevelNum())) {
						qiMoValueDai+=obj.getQiMoValueDai();
					}
					
					b1 = new BigDecimal(obj.getQiMoValueDai().toString());
					b2 = new BigDecimal("100");
					obj.setQiMoValueDai(b1.divide(b2).doubleValue());
				}
				
			}
			
			KmYuEBiao zj = new KmYuEBiao();
			
			if(qiChuValueJie!=0){
				
				b1 = new BigDecimal(qiChuValueJie.toString());
				b2 = new BigDecimal("100");
				zj.setQiChuValueJie(b1.divide(b2).doubleValue());
			}
			
			if(qiChuValueDai!=0){
				
				b1 = new BigDecimal(qiChuValueDai.toString());
				b2 = new BigDecimal("100");
				zj.setQiChuValueDai(b1.divide(b2).doubleValue());
			}
			
			if(bqfsValueJie!=0){
				
				b1 = new BigDecimal(bqfsValueJie.toString());
				b2 = new BigDecimal("100");
				zj.setBqfsValueJie(b1.divide(b2).doubleValue());
			}
			
			if(bqfsValueDai!=0){
				
				b1 = new BigDecimal(bqfsValueDai.toString());
				b2 = new BigDecimal("100");
				zj.setBqfsValueDai(b1.divide(b2).doubleValue());
			}
			
			if(bnljValueJie!=0){
				
				b1 = new BigDecimal(bnljValueJie.toString());
				b2 = new BigDecimal("100");
				zj.setBnljValueJie(b1.divide(b2).doubleValue());
			}
			
			if(bnljValueDai!=0){
				
				b1 = new BigDecimal(bnljValueDai.toString());
				b2 = new BigDecimal("100");
				zj.setBnljValueDai(b1.divide(b2).doubleValue());
			}
			
			if(qiMoValueJie!=0){
				
				b1 = new BigDecimal(qiMoValueJie.toString());
				b2 = new BigDecimal("100");
				zj.setQiMoValueJie(b1.divide(b2).doubleValue());
			}
			
			if(qiMoValueDai!=0){
				
				b1 = new BigDecimal(qiMoValueDai.toString());
				b2 = new BigDecimal("100");
				zj.setQiMoValueDai(b1.divide(b2).doubleValue());
			}
			
			zj.setDicName("合计");
			zj.setLevelNum("1");
			dataList.add(dataList.size(), zj);
			
			modelMap.put("msg", Constants.SUCCESS);
			modelMap.put("dataList", dataList);
			
			this.ajax(response, modelMap);
			
			return null;
		} catch (Exception e) {
			this.logException(e);
			modelMap.put("msg", "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
			return this.ajax(response, modelMap);
		}
	}
	
	@RequestMapping("/mingXiList")
	@DoLog(cnContent = "查看明细账")
	@Permission(name="kmYuEBiao.mxView")
	public ModelAndView mingXiList(HttpServletRequest request, HttpServletResponse response, KmYuEBiao qvo) throws Exception {
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		//当前账期
		JieZhang jz = (JieZhang) request.getSession().getAttribute(Constants.CURRENT_JIE_ZHANG);
		ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
		
		modelMap.put("minDate", zt.getQyYear() + "-" + StringUtils.leftPad(zt.getQyMonth() + "", 2, "0"));
		modelMap.put("maxDate", jz.getJzYear() + "-" + StringUtils.leftPad(jz.getJzMonth() + "", 2, "0"));

		int jz_year = jz.getJzYear();
		int jz_month = jz.getJzMonth();

		String startTimeStr = jz_year + "-" + StringUtils.leftPad(jz_month + "", 2, "0");
		modelMap.put("startTimeStr", startTimeStr);
		modelMap.put("endTimeStr", startTimeStr);
		
		String kmMingXiCode = (String)request.getSession().getAttribute("kmMingXiCode");
		String kmMingXiName = (String)request.getSession().getAttribute("kmMingXiName");
		String startTimeStr2 = (String)request.getSession().getAttribute("startTimeStr");
		String endTimeStr = (String)request.getSession().getAttribute("endTimeStr");
		
		if(StringUtils.isNotBlank(startTimeStr2)){
			modelMap.put("startTimeStr", startTimeStr2);
		}
		if(StringUtils.isNotBlank(endTimeStr)){
			modelMap.put("endTimeStr", endTimeStr);
		}
		if(StringUtils.isNotBlank(kmMingXiCode)){
			modelMap.put("kmMingXiCode", kmMingXiCode);
		}
		if(StringUtils.isNotBlank(kmMingXiName)){
			modelMap.put("kmMingXiName", kmMingXiName);
		}
		request.getSession().removeAttribute("kmMingXiCode");
		request.getSession().removeAttribute("kmMingXiName");
		request.getSession().removeAttribute("startTimeStr");
		request.getSession().removeAttribute("endTimeStr");

		return new ModelAndView("kmYuEBiao/mingXiList").addAllObjects(modelMap);
	}
	
	@RequestMapping("/kmCodeTree")
	@DoLog(cnContent = "加载树节点")
	public void tCollectStatisticChildTree(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
		DickmQueryVo vo = new DickmQueryVo();
		vo.setZhangTaoId(zt.getUuid());
		
		List<DickmShowVo> dataList = dickmService.searchTreeList(vo);
		
		List<ZTreeComm> ZTreeCommList = new ArrayList<ZTreeComm>();
		//封装成树结果
		for (DickmShowVo obj : dataList) {
			ZTreeComm ZTreeComm = new ZTreeComm();
			ZTreeComm.setpId(obj.getParentDicCode());
			ZTreeComm.setId(obj.getDicCode());
			ZTreeComm.setName(obj.getDicCode()+" "+obj.getDicName());
			if(obj.getChileCount()>0){
				ZTreeComm.setIsParent("true");
			}else{
				ZTreeComm.setIsParent("false");
			}
			ZTreeCommList.add(ZTreeComm);
		}
		this.ajax(response, ZTreeCommList);
	}

	@RequestMapping("/mingXiListAjaxPage") 
	@DoLog(cnContent="查看明细账列表ajax分页")
	@Permission(name="kmYuEBiao.mxView")
	public String mingXiListAjaxPage(HttpServletRequest request, HttpServletResponse response, PingZhengQueryVo queryVo) throws Exception{
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		try {
			Pager<PingZhengShowVo> p = new Pager<PingZhengShowVo>();
			String currentPage = request.getParameter(Pager.MY_PAGINATION_CURRENT_PAGE);
			p.setCurrentPage(Integer.parseInt(currentPage == null ? "1" : currentPage));
			
			ZhangTao zt = (ZhangTao) request.getSession().getAttribute(Constants.CURRENT_ZHANG_TAO);
			String startTimeStr = request.getParameter("startTimeStr");
			String endTimeStr = request.getParameter("endTimeStr");
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM");
			Map<String, Date> datemap = null;
			Date startTime = null;
			Date endTime = null;
			String tempDateStr;
			//如果开始时间和结束时间不为空
			if (StringUtils.isNotBlank(startTimeStr) && StringUtils.isNotBlank(endTimeStr)) {
				
				modelMap.put("startTimeStr", startTimeStr);
				modelMap.put("endTimeStr", endTimeStr);
				
				startTimeStr = startTimeStr + "-01";
				endTimeStr = endTimeStr + "-01";
				datemap = DateTimeUtils.getMonthEndDateForStartDate(sdf.parse(endTimeStr));
				startTime = sdf.parse(startTimeStr);
				endTime = datemap.get(Constants.END_TIME);
			}else{
				if (StringUtils.isNotBlank(startTimeStr)) {
					tempDateStr = startTimeStr + "-01";
				}else if (StringUtils.isNotBlank(endTimeStr)){
					tempDateStr = endTimeStr + "-01";
				}else{
					//当前账期
					JieZhang jz = (JieZhang) request.getSession().getAttribute(Constants.CURRENT_JIE_ZHANG);
					int jz_year = jz.getJzYear();
					int jz_month = jz.getJzMonth();
					tempDateStr = jz_year + "-" + StringUtils.leftPad(jz_month + "", 2, "0") + "-01";
				}
				
				datemap = DateTimeUtils.getMonthEndDateForStartDate(sdf.parse(tempDateStr));
				startTime = datemap.get(Constants.START_TIME);
				endTime = datemap.get(Constants.END_TIME);
				
				modelMap.put("startTimeStr", sdf2.format(startTime));
				modelMap.put("endTimeStr", sdf2.format(startTime));
			}
			
			if(startTime.getTime()>=endTime.getTime()){
				modelMap.put("msg", "会计期间：开始期间不能大于结束期间!");
				return this.ajax(response,modelMap);
			}
			
			String dicCode = request.getParameter("dicCode");
			Dickm dickm = dickmService.getByDicCode(dicCode);
			int year;
			
			queryVo.setStartTime(startTime);
			queryVo.setEndTime(endTime);
			queryVo.setCompanyId(zt.getUuid());
			queryVo.setDicCode(dicCode);
			queryVo.setYueFx(dickm.getYueFx());
			//通过开始时间获取本年年初时间 一般是  开始时间年的1月1号
			year = DateTimeUtils.getYear(queryVo.getStartTime());
			queryVo.setYearStartTime(sdf.parse(year+"-01"+"-01"));
			
			//设置账套启用时间
			queryVo.setQiYongStartTime(sdf.parse(zt.getQyYear()+"-"+StringUtils.leftPad(zt.getQyMonth()+"", 2, '0')+"-01"));
			
			List<PingZhengQueryVo> parmLiat = new LinkedList<PingZhengQueryVo>();
			PingZhengQueryVo vo = null;
			Date lastMonthFirstDate = null;
			Date tempDate = startTime;
			while(true){
				vo = new PingZhengQueryVo();
				datemap = DateTimeUtils.getMonthEndDateForStartDate(tempDate);
				vo.setStartTime(datemap.get(Constants.START_TIME));
				vo.setEndTime(datemap.get(Constants.END_TIME));
				vo.setCompanyId(zt.getUuid());
				vo.setDicCode(dicCode);
				vo.setYueFx(dickm.getYueFx());
				//通过开始时间获取本年年初时间 一般是  开始时间年的1月1号
				year = DateTimeUtils.getYear(tempDate);
				vo.setYearStartTime(sdf.parse(year+"-01"+"-01"));
				parmLiat.add(vo);
				
				lastMonthFirstDate = DateTimeUtils.getLastMonthFirstDate(tempDate);
				if(DateTimeUtils.isBefore(lastMonthFirstDate, endTime)){
					tempDate = lastMonthFirstDate;
				}else{
					break;
				}
			}
			
			Pager<PingZhengShowVo> pager = pingZhengService.mingXiListAjaxPage(p, queryVo, parmLiat);
			
			List<PingZhengShowVo> dataList = pager.getDataList();
			BigDecimal b1 = null;
			BigDecimal b2 = null;
			for(PingZhengShowVo pzvo:dataList) {
				if(pzvo.getJfje()!=null) {
					b1 = new BigDecimal(pzvo.getJfje().toString());
					b2 = new BigDecimal("100");
					pzvo.setJfje(b1.divide(b2).doubleValue());
				}
				
				if(pzvo.getDfje()!=null) {
					b1 = new BigDecimal(pzvo.getDfje().toString());
					b2 = new BigDecimal("100");
					pzvo.setDfje(b1.divide(b2).doubleValue());
				}
				
				if(pzvo.getYuE()!=null) {
					b1 = new BigDecimal(pzvo.getYuE().toString());
					b2 = new BigDecimal("100");
					pzvo.setYuE(b1.divide(b2).doubleValue());
				}
			}
			
			this.genPageJson(response, pager);
			return null;
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}
	
	@RequestMapping("/setkmCode")
	public String setkmCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String kmMingXiCode = request.getParameter("kmMingXiCode");
		String startTimeStr = request.getParameter("startTimeStr");
		String endTimeStr = request.getParameter("endTimeStr");
		Dickm dickm = dickmService.getByDicCode(kmMingXiCode);
		if(dickm !=null){
			request.getSession().setAttribute("kmMingXiName", dickm.getFullName());
		}
		request.getSession().setAttribute("kmMingXiCode", kmMingXiCode);
		request.getSession().setAttribute("startTimeStr", startTimeStr);
		request.getSession().setAttribute("endTimeStr", endTimeStr);
		return this.ajax(response, Constants.SUCCESS);
	}

}
